package com.offics.frame.application.service;

import com.offics.frame.application.dto.auth.AuthResponse;
import com.offics.frame.application.dto.auth.LoginRequest;
import com.offics.frame.application.dto.auth.RegisterRequest;
import com.offics.frame.domain.entity.User;
import com.offics.frame.domain.service.UserService;
import com.offics.frame.infrastructure.security.JwtTokenProvider;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class AuthService {

    private final UserService userService;
    private final JwtTokenProvider jwtTokenProvider;

    /**
     * 用户注册
     */
    public AuthResponse register(RegisterRequest request) {
        // 创建用户实体
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(request.getPassword());
        user.setNickname(request.getNickname());
        user.setAvatar(request.getAvatar());
        user.setEmail(request.getEmail());
        user.setPhone(request.getPhone());

        // 注册用户
        User registeredUser = userService.register(user);

        // 生成JWT令牌
        UserDetails userDetails = org.springframework.security.core.userdetails.User.builder()
                .username(registeredUser.getUsername())
                .password(registeredUser.getPassword())
                .roles("USER")
                .build();
        String token = jwtTokenProvider.generateToken(userDetails);

        // 返回认证响应
        return AuthResponse.builder()
                .token(token)
                .username(registeredUser.getUsername())
                .nickname(registeredUser.getNickname())
                .avatar(registeredUser.getAvatar())
                .build();
    }

    /**
     * 用户登录
     */
    public AuthResponse login(LoginRequest request) {
        // 登录用户
        User user = userService.login(request.getUsername(), request.getPassword());

        // 生成JWT令牌
        UserDetails userDetails = org.springframework.security.core.userdetails.User.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .roles("USER")
                .build();
        String token = jwtTokenProvider.generateToken(userDetails);

        // 返回认证响应
        return AuthResponse.builder()
                .token(token)
                .username(user.getUsername())
                .nickname(user.getNickname())
                .avatar(user.getAvatar())
                .build();
    }
}